package authentication

import "io"

//TODO 自定义aes key

const (
	MaxAuthPacketSize = 4096
)

type PacketType int

const (
	PacketTypeUnknown = 255
	PacketTypeMsg     = 0
	PacketTypeReport  = 1
	PacketTypeLogin   = 10
	PacketTypeLogout  = 11
)

//
// TransportPacket
// @Description:
//
type TransportPacket struct {
	Type    PacketType
	UUID    string
	Payload []byte
}

//
// NewTransportPacket
// @Description:
// @return *TransportPacket
//
func NewTransportPacket() *TransportPacket {
	return &TransportPacket{
		Type: PacketTypeUnknown,
	}
}

//
// Encode
// @Description:
// @receiver tp
// @return []byte
//
func (tp *TransportPacket) Encode() []byte {
	var b []byte
	b = append(b, byte(tp.Type))
	b = append(b, []byte(tp.UUID)...)
	b = append(b, tp.Payload...)
	base64, err := EncodeAESBase64(b)
	if err != nil {
		return nil
	}
	return []byte(base64)
}

//
// Decode
// @Description:
// @receiver tp
// @return []byte
//
func (tp *TransportPacket) Decode(bytes []byte) error {
	if b, err := DecodeAESBase64(string(bytes)); err == nil {
		tp.Type = PacketType(b[0])
		tp.UUID = string(b[1:33])
		tp.Payload = b[33:]
	} else {
		return err
	}
	return nil
}

//
// Send
// @Description:
// @receiver tp
// @param rwc
//
func (tp *TransportPacket) Send(rwc io.ReadWriteCloser) error {
	_, err := rwc.Write(tp.Encode())
	return err
}
